<?php

namespace app\api\model;

use app\admin\model\Area;
use app\admin\model\Car;
use app\admin\model\College;
use app\admin\model\Config;
use app\admin\model\Staff;
use app\admin\service\User;
use Endroid\QrCode\QrCode;
use think\Db;
use think\Exception;
use think\Model;

class Order extends Model
{

    public function getStatusAttr($value)
    {
        $status = [0 => "已预约", 1 => "使用中", 2 => "已归还", 3 => "已取消", 4 => "超时自动取消"];
        return ['value' => $status[$value], 'status' => $value];
    }

    public function area()
    {
        return $this->belongsTo('app\admin\model\Area', 'aid', 'id')->field('name,id')->setEagerlyType(0);
    }

    public function car()
    {
        return $this->belongsTo('app\admin\model\Car', 'carId', 'id')->field('number,id')->setEagerlyType(0);
    }

    public function staff()
    {
        return $this->belongsTo('app\admin\model\Staff', 'uid', 'id')->setEagerlyType(0);
    }

    public function admin()
    {
        return $this->belongsTo('app\admin\model\Staff', 'adminId', 'id')->setEagerlyType(0);
    }

    protected $autoWriteTimestamp = true;
    protected $updateTime = 'updateTime';

    protected $createTime = 'createTime';


    public function reservationCar($param)
    {
        try {
            Db::startTrans();

            if (!$param['makeTime'] || !$param['aid']) {
                throw new Exception("缺少参数");
            }
            if (strtotime($param['makeTime']) < time()) {
                throw new Exception("请选取正确的时间");
            }
            //查询库存
            $reservation = Area::where(['id' => $param['aid'], 'status' => 1])->find();
            if (!$reservation->id) {
                throw new Exception("该区域已下架，请刷新后重试！");
            }


//            查询是否有已经在使用的车辆
            $order = (new Order)->where(['uid' => $param['uid'], 'status' => [0, 1]])->count();
            if ($order) {
                throw new Exception("你已经有预约的车辆订单");
            }


            //查询该厂区已经在使用的车辆

            $makeCar = (new Order())->where(['aid' => $param['aid'], 'status' => [0, 1]])->select()->toArray();
            $makeCarId = [];
            if ($makeCar) {
                $makeCarId = array_column($makeCar, 'carId');
            }

            //查询剩余车辆Id,并随机分配一个
            $car = (new Car)->where(['status' => 1, 'aid' => $param['aid']])
                ->whereNotIn('id', $makeCarId)
                ->orderRaw('rand()')
                ->find();
            if (!$car) {
                throw new Exception('该区域无车辆信息');
            }

            $param['carId'] = $car->id;
            $param['makeTime'] = strtotime($param['makeTime']);
            $param['qrcode'] = $this->generateAndSave($param['uid']);
            if (!(new Order())->allowField(true)->save($param)) {
                throw new Exception('预约失败，请重新尝试');
            }

            //更新库存
            if (!(new Area())->where(['id' => $param['aid']])->setDec('stock')) {
                throw new Exception('预约失败，请重新尝试');
            }
            Db::commit();
            $config = (new Config)->where(['id' => 15])->find();
            return ['code' => 200, 'msg' => '预约成功', 'data' => ['closeOrder' => $config->value]];


        } catch (Exception $e) {
            Db::rollback();
            return ['code' => 201, 'msg' => $e->getMessage(), 'data' => []];
        }
    }


    public function getUserMakeCarInfo($params)
    {
        $makeCar = self::where(['uid' => $params['uid']])
            ->with(['area', 'car'])
            ->order('createTime DESC')
            ->find();
        if ($makeCar) {
            $config = (new Config)->where(['id' => 15])->find();
            $makeCar['closeOrderTime'] = $makeCar['makeTime'];
            $makeCar['timeOut'] = time() - $makeCar['returnTime'] > 0 ? self::secondTime(time() - $makeCar['returnTime']) : '';
            $makeCar['close'] = $config['value'];
        }
        return ['code' => 200, 'msg' => '获取成功', 'data' => $makeCar];

    }


    public static function secondTime($seconds = 0)
    {
        $duration = '';

        $seconds = (int)$seconds;
        if ($seconds <= 0) {
            return $duration . '0秒';
        }

        list($day, $hour, $minute, $second) = explode(' ', gmstrftime('%j %H %M %S', $seconds));

        $day -= 1;
        if ($day > 0) {
            $duration .= (int)$day . '天';
        }
        if ($hour > 0) {
            $duration .= (int)$hour . '小时';
        }
        if ($minute > 0) {
            $duration .= (int)$minute . '分钟';
        }
        if ($second > 0) {
            $duration .= (int)$second . '秒';
        }

        return $duration;
    }


    public function scanQrcode($params)
    {

        try {
            Db::startTrans();
            $makeCarInfo = self::where(['uid' => $params['staffId']])->order('createTime DESC')->find();
            $status = $makeCarInfo->status['status'];

            $staffAdmin = (new Staff())->where(['id' => $params['uid']])->find();
            if (!$staffAdmin) {
                throw new Exception('该区域无管理员，暂不可借车');
            }


            $makeCarInfo->adminId = $params['uid'];
            //判断是预约车辆还是还车
            if ($status == 0) {

                //判断该区域是否可以使用
                if ($makeCarInfo->aid != $staffAdmin['aid']) {
                    throw new Exception("不允许在该区域操作");
                }

                $config = (new Config())->where(['id' => 16])->field('value')->find();
                $makeCarInfo->returnTime = time() + $config->value * 60 * 60;
                $makeCarInfo->getCarTime = time();
                //开始预约车辆
                $makeCarInfo->status = 1;
            } elseif ($status == 1) {
                $makeCarInfo->status = 2;
                $makeCarInfo->returnCarTime = time();

                //更新车辆区域
                $car = Car::get($makeCarInfo->carId);
                $car->aid = $staffAdmin->aid;
                if (!$car->save()) {
                    throw new Exception("归还失败，请重新尝试");
                }

            } else {
                throw new Exception("数据异常");
            }

            if (!$makeCarInfo->save()) {
                throw new Exception("归还失败，请重新尝试");
            }

            $car = (new Car())->where(['id' => $makeCarInfo->carId])->find();
            if (!$car) {
                throw new Exception("车辆不存在，请联系管理员");
            }
            Db::commit();
            if ($status == 0) {
                return ['code' => 200, 'msg' => '预约成功', 'data' => ['status' => $status, 'carNumber' => $car['number']]];
            } elseif ($status == 1) {
                return ['code' => 200, 'msg' => '还车成功', 'data' => ['status' => $status]];
            } else {
                throw new Exception("数据异常");
            }
        } catch (Exception $e) {
            Db::rollback();
            return ['code' => 202, 'msg' => $e->getMessage()];
        }

    }


    //取消预约
    public function cancelOrder($param)
    {
//        return ['code' => 200, 'msg' => '取消成功','data' =>''];
        try {
            Db::startTrans();
            //查询订单
            $makeCar = self::where(['id' => $param['id']])->find();
            if (!$makeCar) {
                throw new Exception("未查到订单");
            }
            $makeCar->status = 3;
            if (!$makeCar->save()) {
                throw new Exception("取消失败，请重新尝试");
            }

            if (!Area::where(['id' => $makeCar->aid])->setInc('stock')) {
                throw new Exception("库存返回失败，请重新尝试");
            }

            Db::commit();
            return ['code' => 200, 'msg' => '取消成功', 'data' => ''];
        } catch (Exception $e) {
            Db::rollback();
            return ['code' => 201, 'msg' => $e->getMessage()];
        }
    }


    public function agains($param)
    {
//        return ['code' => 200, 'msg' => '取消成功','data' =>''];
        try {
            Db::startTrans();
            //查询订单
            $makeCar = self::where(['id' => $param['id']])->find();
            if (!$makeCar) {
                throw new Exception("未查到订单");
            }

            if (!Area::where(['id' => $makeCar->aid])->setInc('stock')) {
                throw new Exception("库存返回失败，请重新尝试");
            }

            if (!$makeCar->delete()) {
                throw new Exception("操作失败，请重新尝试");
            }

            Db::commit();
            return ['code' => 200, 'msg' => '取消成功', 'data' => ''];
        } catch (Exception $e) {
            Db::rollback();
            return ['code' => 201, 'msg' => $e->getMessage()];
        }
    }


    //生成二维码
    public function generateAndSave($uid)
    {
        $qrcode = new QrCode($uid);
        $imageData = $qrcode->writeString();
        return base64_encode($imageData);
    }

    public function getUserMakeCarStatus($param)
    {
        $makeCar = self::where(['uid' => $param['uid']])->order('createTime desc')->find();
        return ['code' => 200, 'msg' => '获取成功', 'data' => $makeCar];
    }
}
